package org.west.sky.experience.bigtalkdp.chapter17;

/**
 * @author: chz
 * @date: 2023/7/3
 * @description: 单例模式--懒汉模式
 */
public class Singleton {

    private static Singleton singleton = null;
    private volatile static Singleton singleton2 = null;

    private Singleton() {

    }

    /**
     * 存在线程安全问题
     *
     * @return
     */
    public static Singleton instance() {
        if (null == singleton) {
            singleton = new Singleton();
        }
        return singleton;
    }

    /**
     * 并发锁保证线程安全，效率低，只有第一次初始化对象才需要加锁
     *
     * @return
     */
    public static synchronized Singleton instance2() {
        if (null == singleton) {
            singleton = new Singleton();
        }
        return singleton;
    }

    /**
     * 双重判断并发锁保证线程安全
     *
     * @return
     */
    public static Singleton instance3() {
        if (null == singleton) {
            synchronized (Singleton.class) {
                if (null == singleton) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    /**
     * 双重判断并发锁保证线程安全、加volatile禁止指令重排序，保证线程安全
     *
     * @return
     */
    public static Singleton instance4() {
        if (null == singleton2) {
            synchronized (Singleton.class) {
                if (null == singleton2) {
                    singleton2 = new Singleton();
                }
            }
        }
        return singleton2;
    }
}
